#!/usr/bin/env python
# -*- coding: utf-8 -*-

import urllib2
import json


# 利用RESTful API的Cayley工具类
class CayleyUtil(object):

    # Gremlin Query
    query_gremlin = "/api/v1/query/gremlin"
    query_shape_gremlin = "/api/v1/shape/gremlin"

    # MQL Query
    query_mql = "/api/v1/query/mql"
    query_shape_mql = "/api/v1/shape/mql"

    # Write Commands
    write = "/api/v1/write"
    delete = "/api/v1/delete"

    def __init__(self, host="localhost", port="64210"):
        self.__url_prefix = "http://" + host + ":" + port

    @staticmethod
    def __curl_cayley(url, values):
        request = urllib2.Request(url, values)
        response = urllib2.urlopen(request)
        return response.read()

    def query(self, values, gremlin=True):
        url = self.__url_prefix
        url += self.query_gremlin if gremlin else self.query_mql
        return CayleyUtil.__curl_cayley(url, values)

    def query_shape(self, values, mql=False):
        url = self.__url_prefix
        url += self.query_shape_mql if mql else self.query_shape_gremlin
        return CayleyUtil.__curl_cayley(url, values)

    def insert_quads(self, values):
        url = self.__url_prefix + self.write
        result = CayleyUtil.__curl_cayley(url, values)
        data = json.loads(result)
        return False if data.get("error", None) else True

    def delete_quads(self, values):
        url = self.__url_prefix + self.delete
        result = CayleyUtil.__curl_cayley(url, values)
        data = json.loads(result)
        return False if data.get("error", None) else True


if __name__ == "__main__":
    cayley_util = CayleyUtil()

    gremlin_query_test = "g.V().Tag(\"source\").Out(\"is-a\", \"relation\").Tag(\"target\").All()"
    print cayley_util.query(gremlin_query_test)

    # mql_query_test = """
    # [{
    #     "id": "alice",
    #     "follows": "bob",
    #     "is": "cool"
    # }]"""
    # print cayley_util.query(mql_query_test, False)

    # insert_test = """
    # [{
    #     "subject": "panda",
    #     "predicate": "follows",
    #     "object": "bob"
    # },
    # {
    #     "subject": "panda",
    #     "predicate": "follows",
    #     "object": "alice"
    # }]"""
    # print cayley_util.insert_quads(insert_test)
    #
    # gremlin_query_test = "graph.Vertex(\"panda\").Out(\"follows\").All()"
    # print cayley_util.query(gremlin_query_test)
    #
    # delete_test = """
    # [{
    #     "subject": "panda",
    #     "predicate": "follows",
    #     "object": "bob"
    # },
    # {
    #     "subject": "panda",
    #     "predicate": "follows",
    #     "object": "alice"
    # }]"""
    # print cayley_util.delete_quads(delete_test)
    #
    # gremlin_query_test = "graph.Vertex(\"panda\").Out(\"follows\").All()"
    # print cayley_util.query(gremlin_query_test)

















